package com.datasure.demo.webSocket.services;

import com.alibaba.fastjson2.JSON;
import com.datasure.demo.webSocket.config.RequestInfo;
import com.datasure.demo.webSocket.config.ServiceManage;
import io.netty.channel.Channel;
import io.netty.channel.ChannelId;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public abstract class BasicService<T> {

    protected abstract String bussineType();

    /**
     * 是否定时触发
     * true 定时触发
     * false
     * @return
     */
    protected abstract Boolean isSchedule();

    protected Map<Long, RequestInfo> userMap = new ConcurrentHashMap<>();

    protected Map<ChannelId, Long> channelUserMap = new ConcurrentHashMap<>();



    @PostConstruct
    protected void init(){
        ServiceManage.registryService(bussineType(), this);
        log.info("registryService done");
    }

    public void addUser(ChannelId channelId, RequestInfo requestInfo) {
        log.info("addUser channelId:{}",channelId.asLongText());
        channelUserMap.put(requestInfo.getChannel().id(), requestInfo.getUserId());
        userMap.put(requestInfo.getUserId(), requestInfo);
    }

    public void removeUser(ChannelId channelId){
        log.info("removeUser channelId:{}",channelId.asLongText());
        Long userId = channelUserMap.get(channelId);
        userMap.remove(userId);
        channelUserMap.remove(channelId);
    }

    public abstract T getMessage(Long userId, RequestInfo requestInfo);

    public void pushMessage(Long userId) {
        RequestInfo requestInfo = userMap.get(userId);
        Channel channel = requestInfo.getChannel();
        T message = getMessage(userId, requestInfo);
        TextWebSocketFrame res = new TextWebSocketFrame(JSON.toJSONString(message));
        channel.writeAndFlush(res);
    }

}
